package com.dai.rpc.loadbanlance;

import com.dai.rpc.message.RpcRequest;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Set;

public abstract class AbstractLoadBalance implements LoadBalance {

    @Override
    public String selectServiceAddress(List<String> serviceUrlList, RpcRequest rpcRequest) {

        // 如果服务列表为空，返回空
        if(serviceUrlList == null || serviceUrlList.isEmpty()){
            return null;
        }
        // 如果服务列表只有一个实例，返回唯一的可用实例
        if(serviceUrlList.size() == 1){
            return serviceUrlList.get(0);
        }
        return doSelect(serviceUrlList, rpcRequest);
    }

    protected abstract String doSelect(List<String> serviceUrlList, RpcRequest rpcRequest);


    @Override
    public InetSocketAddress loadBalance(Set<String> services) {
        if(services == null || services.isEmpty()){
            return null;
        }
        return doLoadBalance(services);
    }

    protected abstract InetSocketAddress doLoadBalance(Set<String> services);

}
